#!/bin/bash
#当前用户密码
PASS=123
#设置局域网内最小和最大地址的位数
BEGIN=10
END=254

#指定网卡
NETWORK_CARD="ens33"

#获取网卡的IP地址
IP=`ip a s ens33 | awk -F'[ /]+' 'NR==3{print $3}'`
#IP=$(ip a s "$NETWORK_CARD" | awk -F'[ /]+' 'NR==3{print $3}')
#删除IP最后一个点之后的内容，结果如：192.168.10
NET=${IP%.*}.

#将系统信息变量形式导入当前shell环境。
#执行. /etc/os-release后，这些变量（如NAME、VERSION、ID等）就会被导入到当前的shell环境中
. /etc/os-release

color () {
  RES_COL=60
  MOVE_TO_COL="echo -en \\033[${RES_COL}]G"
  SETCOLOR_SUCCESS="echo -en \\033[1;32m"
  SETCOLOR_FAILURE="echo -en \\033[1;31m"
  SETCOLOR_WARNING="echo -en \\033[1;33m"
  SETCOLOR_NORMAL="echo -en \E[0m"
  echo -n "$1" && $MOVE_TO_COL
  echo -n "["
  if [ $2 = "success" -o $2 = "0" ] ;then
      ${SETCOLOR_SUCCESS}
      echo -n $"  OK  "
  elif [ $2 = "failure" -o $2 = "1" ] ;then
      ${SETCOLOR_FAILURE}
      echo -n $"FAILED"
  else
      ${SETCOLOR_WARNING}
      echo -n $"WARNING"
  fi
  ${SETCOLOR_NORMAL}
  echo -n "]"
  echo
}

#安装sshpass
install_sshpass() {
  if [[ $ID =~ centos|rocky|rhel ]];then
    rpm -q sshpass &> /dev/null || yum -y install sshpass
  else
    dpkg -l sshpass &> /dev/null || { sudo apt update;sudo apt -y install sshpass; }
  fi
  if [ $? -ne 0 ];then
    color '安装 sshpass 失败' 1
    exit 1
  fi
}

#扫描网络内主机
scan_host() {
  [ -e ./SCANIP.log ] && rm -f SCANIP.log
  for((i=$BEGIN;i<="$END";i++));do
    ping -c 1 -w 1 ${NET}$i &> /dev/null && echo "${NET}$i" >> SCANIP.log &
  done
  wait
}

#推送ssh_key
push_ssh_key() {
  #生成ssh key
  [ -e ~/.ssh/id_rsa ] || ssh-keygen -P "" -f ~/.ssh/id_rsa
  sshpass -P $PASS ssh-copy-id -o StrictHostKeyChecking=no ${USER}@$IP  &>/dev/null

  ip_list=(`sort -t . -k 4 -n  SCANIP.log`)
  for ip in ${ip_list[*]};do
      sshpass -p $PASS scp -o StrictHostKeyChecking=no -r ~/.ssh ${USER}@$IP  &>/dev/null
  done

  #把.ssh/known_hosts拷贝到所有主机，使他们第一次互相访问时不需要输入yes回车
  for ip in ${ip_list[*]};do
      scp ~/.ssh/known_hosts ${USER}@${ip}:.ssh/    &>/dev/null
      color "$ip" 0
  done
}

install_sshpass
scan_host
push_ssh_key
